package com.tywj.panda.customer.usercenter.center

import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.tywj.panda.customer.common.event.UserEvent
import com.tywj.panda.customer.common.http.PDStringCallback
import com.tywj.panda.customer.common.manager.AuthorityManager
import com.tywj.panda.customer.common.view.base.MyBaseActivity
import com.tywj.panda.customer.usercenter.api.UserCenterApi
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.route.RouteParam
import com.tywj.panda.customer.usercenter.R
import com.tywj.panda.customer.usercenter.route.UserCenterRoute
import kotlinx.android.synthetic.main.user_activity_nickname.*

@Route(path = UserCenterRoute.USER_NICKNAME)
class UserNickNameActivity : MyBaseActivity() {
    override fun getLayoutID(): Int = R.layout.user_activity_nickname

    companion object {
        const val PARAMS_NICK_NAME = "nickName"
    }

    private var nickName = ""

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)

        nickName = RouteParam(this).getString(PARAMS_NICK_NAME)

        etNickName.setText(nickName)

        etNickName.setSelection(nickName.length)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))

    }

    override fun initListener() {
        super.initListener()


        ivDelete.onClick {
            etNickName.setText("")
        }

        titleLayout.getRightTextView().onClick {
            val nickName = etNickName.text.toString().trim()

            if (nickName.isNotEmpty()) {
                loadData(nickName)
            } else {
                shortToast("请输入昵称")
            }
        }
    }

    private fun loadData(nickName: String) {
        showLoadingDialog(ResourcesUtil.getString(R.string.common_loading))
        UserCenterApi.saveUserInfo(nickName = nickName).attachToLifecycle(this).execute(object : PDStringCallback() {

            override fun success(message: String) {
                UserEvent.loadUserDataSuccessEvent.post(AuthorityManager.uid)
                shortToast("保存成功")
                finish()
            }

            override fun error(code: Int, message: String) {
                super.error(code, message)
                shortToast(message)
            }

            override fun onComplete() {
                super.onComplete()
                dismissLoadingDialog()
            }
        })
    }
}